const express = require('express')
const multipart = require('connect-multiparty')
const path = require('path')
const fse = require('fs-extra')
const fs = require('fs')
const atob = require('atob')
const bodyParser = require('body-parser')
const multer = require('multer')
const app = express()
const chunkPath = '~/uploadCache'
const storage = multer.diskStorage({
    destination: chunkPath,
})
const baseUpload = multer({ storage })

const upload = baseUpload.single('file')
const uploadDir = path.resolve(__dirname, 'upload-file')
const uploadMiddleware = (req, res, next) => {
    upload(req, res, (err) => {
        if (err) {
            // 进行错误捕获
            // console.log('middleware')
            res.json({ code: -1, msg: err.toString() });
        } else {
            next();
        }
    });
};
// app.use(multipart({
//     uploadDir: path.resolve(__dirname, 'upload-file')
// }))
app.use(bodyParser.json())
// app.use(bodyParser.text())
app.use(bodyParser.urlencoded({ extended: true }))
const router = express.Router()

registerMoreRouter(router)

app.use(router)

const port = process.env.PORT || 8080

module.exports = app.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`)
})

function registerMoreRouter(router) {
    fse.ensureDir(uploadDir)
    router.get('/more/get', function (req, res) {
        res.json(req.cookies)
    })
    router.post('/more/post', function (req, res) {
        res.json(req.body)
    })
    router.post('/more/upload', function (req, res) {
        res.json({
            code: 0,
            url: 'aaaaa'
        })
        console.log(req.files)
    })
    router.post('/more/getUploadChunks', function (req, res){
        const splitDir = uploadDir + '/' + req.body.hash
        
        if(fse.existsSync(splitDir)) {
            const chunks = fse.readdirSync(splitDir).sort((a, b) => a - b)
            res.json({
                code: 0,
                data: chunks
            })
        } else {
            res.json({
                code: 0,
                data: []
            })
        }

        
    })
    router.post('/more/upload/single', multipart({
        uploadDir
    }), function (req, res) {
        const splitDir = uploadDir + '/' + req.body.hash
        const upEnd = req.body.id == req.body.total

        // console.log(req)
        console.log(req.body)
        console.log(req.files.file)
        fse.ensureDir(splitDir)
        fse.moveSync(req.files.file.path, splitDir + '/' + req.body.id, {
            overwrite: true
        })
        if (upEnd) {
            const chunks = fse.readdirSync(splitDir).sort((a, b) => a - b)
            let originalFilePath = uploadDir + '/' + req.files.file.originalFilename
            if (fse.ensureFileSync(originalFilePath)) {
                originalFilePath = uploadDir + '/' + new Date().getTime() + req.files.file.originalFilename
            }

            for (let i = 0; i <= chunks.length - 1; i++) {
                let id = chunks[i]
                const chunkFilePath = splitDir + '/' + id
                console.log(chunkFilePath)
                fs.appendFileSync(originalFilePath, fs.readFileSync(chunkFilePath))
                fs.unlinkSync(chunkFilePath)
            }
            // fse.removeSync(splitDir)
            fse.remove(splitDir)
            res.json({
                code: 0,
                id: req.body,
                updateStatus: upEnd,
                href: ''
            })
        } else {
            res.json({
                code: 0,
                id: req.body,
                updateStatus: upEnd
            })
        }


    })
    router.post('/more/auth', function (req, res) {
        const auth = req.headers.authorization
        const [type, credentials] = auth.split(' ')
        console.log(atob(credentials))

        const [username, password] = atob(credentials).split(':')

        if (type === 'Basic' && username === 'xzq') {
            res.json(req.body)
        } else {
            res.status(401)
            res.end('UnAuthorization')
        }
    })
    router.get('/more/304', function (req, res) {
        res.status(304)
        res.end()
    })
    router.get('/more/A', function (req, res) {

        res.end('A')
    })
    router.get('/more/B', function (req, res) {

        res.end('B')
    })
}